<template>
	<view class="addQues">
		<view class="quesType" v-if="tabArr.length>0">
			<uni-tabchange :tabArr="tabArr" :activeTab="activeTab" :isFixed="false"
				@tabChangeSuccess="tabChangeSuccess"></uni-tabchange>
		</view>
		<view class="uploadModule">
			<view class="addBox flex alignCenter" @click="uploadFileClick" v-if="(!fileUrl && activeTab==1)">
				<view class="color666 bold">
					<view>+</view>
					<view>点击上传</view>
				</view>
			</view>
			<!-- 音频 -->
			<view class="audio" v-if="(activeTab==2)">
				<view class="record-layer">
					<view class="record-box">
						<view class="record-btn-layer" v-if="tempFilePath == ''">
							<button class="record-btn" :class="longPress == '1' ? 'record-btn-1' : 'record-btn-2'"
								@longpress="longpressBtn()" @touchend="touchendBtn()">
								<text>{{longPress == '1' ? '按住说话' : '说话中...'}}</text>
							</button>
						</view>
						<view class="record-btn-layer" v-else>
							<button class="record-btn" @click="playBtn()"
								:class="playStatus == '1' ? 'record-btn-2' : 'record-btn-1'">
								<!-- <text>{{playStatus == '1' ? (count+'s') : '点击播放'}}</text> -->
								<text>{{playStatus == '1' ? '播放中...' : '点击播放'}}</text>
							</button>
						</view>
						<!-- 语音音阶动画 -->
						<view class="prompt-layer prompt-layer-1" v-if="longPress == '2'">
							<view class="prompt-loader">
								<view class="em" v-for="(item,index) in 15" :key="index"></view>
							</view>
							<!-- <text class="p">{{'剩余：' + count + 's'}}</text> -->
							<text class="span">松手结束录音</text>
						</view>
						<!-- 删除 -->
						<view class="btn" v-if="delShow" @click.stop="delBtn()" style="margin-top: 10rpx;">
							<text>删除</text>
						</view>
						<!-- 上传 -->
						<view class="btn2"  @click="submitClick1" v-if="delShow" style="margin-top: 10rpx;">
							<text>上传</text>
						</view>
					</view>
				</view>
			</view>
			<view class="rich" v-if="(activeTab==0)">
				<view class="richCon">
					<textarea class="font16" placeholder-class="font14" v-model.trim="answerCon" cols="30" rows="10"
						placeholder="请输入回答内容"></textarea>
				</view>
				<view class="flex alignCenter imgBox">
					<image src="@/static/image/icons/pic.png" mode="widthFix" @click="selectImage"></image>
				</view>
				<uni-imgbox v-if="imgArr.length>0" :imgArr="imgArr"></uni-imgbox>
			</view>
			<view class="hasVideo" v-if="(fileUrl && activeTab==1)">
				<video controls :src="fileUrl"></video>
			</view>
		</view>
		<view class="noWidthBtn" v-if="(fileUrl && activeTab!=0)" @click="uploadFileClick">重新上传</view>
		<view class="fixedBottomBtn" @click="submitClick"><i class="iconfont icon-fabu"></i>提交</view>
	</view>
</template>

<script>
	const recorderManager = uni.getRecorderManager()
	const innerAudioContext = uni.createInnerAudioContext()
	var init // 录制时长计时器
	var timer // 播放 录制倒计时
	import {
		addAnswer
	} from "@/api/send.js"
	import {
		uploadFile,
		chooseImg,
		requestAndroidPermission
	} from "@/utils/common.js"
	export default {
		data() {
			return {
				activeTab: 1,
				tabArr: [{
					title: '图文'
				}, {
					title: '视频'
				},{
					title: '音频'
				}],
				imgArr: [],
				fileUrl: '',
				placeholder: '开始输入...',
				editorCtx: '',
				list: [],
				voicePath: '',
				seconds: 0,
				quesId: '',
				answerCon: '',
				quesTitle: '',
				count: null, // 录制倒计时
				longPress: '1', // 1显示 按住说话 2显示 说话中
				delShow: false, // 删除提示框显示隐藏
				time: 0, //录音时长
				duration: 600000, //录音最大值ms 600000/10分钟
				tempFilePath: '', //音频路径
				playStatus: 0, //录音播放状态 0:未播放 1:正在播放
				audioUrl:''
			}
		},
		onLoad(option) {
			// 为了防止苹果手机静音无法播放
			uni.setInnerAudioOption({
				obeyMuteSwitch: false
			})
			console.log('回答传参', option)
			this.quesTitle = option.query ? JSON.parse(option.query).title : ''
			this.quesId = JSON.parse(option.query).id
			this.activeTab = 1
			this.tabArr = [{
				title: '图文'
			}, {
				title: '视频'
			}, {
				title: '音频'
			}]
		},
		onReady() {
			uni.setNavigationBarTitle({
				title: `回答：${this.quesTitle}`
			})
		},
		watch:{
			activeTab(){
				this.audioUrl=''
			}
		},
		methods: {
			tabChangeSuccess(obj) {
				console.log('obj', obj)
				this.activeTab = obj.activeTab
				this.fileUrl = ''
			},
			uploadFileClick() {
				// #ifdef APP-PLUS
				let permisionStr = ''
				if (uni.getStorageSync('systemInfo').platform == 'ios') {
					permisionStr = 'photoLibrary'
				} else {
					permisionStr = 'android.permission.READ_EXTERNAL_STORAGE'
				}
				requestAndroidPermission(permisionStr).then((status) => {
					if (status !== 1 || status === false) {
						return
					}
					uni.chooseVideo({
						sourceType: ['album'],
						maxDuration: 60, //120秒，时长，最长支持60s（小程序会预检一次，在选择文件前就会判断时长的设置，>60直接走fail）
						success: (res) => {
							const tempFilePath = res.tempFilePath;
							uni.getVideoInfo({
								src: tempFilePath,
								success: (result) => {
									console.log('获取视频信息', result)
									if (result.size > 15 * 1024 * 1024) {
										// 超过15M不允许上传，官方说的返回的单位是Kb，但手机实际上是b
										uni.showToast({
											icon: 'none',
											title: '视频不能超过15M'
										})
										return
									}
									if (result.duration > 2 * 60) {
										// 超过2分钟不允许上传
										uni.showToast({
											icon: 'none',
											title: '视频不能超过2分钟'
										})
										return
									}
									uploadFile([tempFilePath]).then((successFile) => {
										console.log('文件', successFile)
										this.fileUrl = successFile.url
									})
								}
							})
							console.log('数据', res)

						},
						fail: (err) => {
							console.error('err', err)
							if (err.errMsg.indexOf('cancelled') != -1) {
								uni.showToast({
									title: '您已取消上传',
									icon: 'none'
								})
								return
							}
							uni.showToast({
								title: err.errMsg,
								icon: 'none'
							})
						}
					});
				})
				// #endif
				// #ifdef MP
				uni.chooseVideo({
					sourceType: ['album'],
					maxDuration: 60, //120秒，时长，小程序最长支持60s（小程序会预检一次，在选择文件前就会判断时长的设置，>60直接走fail）
					success: (res) => {
						const tempFilePath = res.tempFilePath;
						uni.getVideoInfo({
							src: tempFilePath,
							success: (result) => {
								console.log('获取视频信息', result)
								if (result.size > 15 * 1024 * 1024) {
									// 超过15M不允许上传，官方说的返回的单位是Kb，但手机实际上是b
									uni.showToast({
										icon: 'none',
										title: '视频不能超过15M'
									})
									return
								}
								if (result.duration > 1 * 60) {
									// 超过1分钟不允许上传
									uni.showToast({
										icon: 'none',
										title: '视频不能超过1分钟'
									})
									return
								}
								uploadFile([tempFilePath]).then((successFile) => {
									console.log('文件', successFile)
									this.fileUrl = successFile.url
								})
							},
							fail: (err) => {
								console.error('err', err)
							}
						})
						console.log('数据', res)

					},
					fail: (err) => {
						console.error('err', err)
						if (err.errMsg.indexOf('cancelled') != -1 || err.errMsg.indexOf('cancel') != -1) {
							uni.showToast({
								title: '您已取消上传',
								icon: 'none'
							})
							return
						}
						uni.showToast({
							title: err.errMsg,
							icon: 'none'
						})
					}
				});
				// #endif

			},
			selectImage() {
				chooseImg(9).then((path) => {
					uni.showLoading({
						title: '上传中',
						mask: true
					})
					path.forEach((val) => {
						uploadFile([val]).then((uploadSucc) => {
							this.imgArr.push(uploadSucc.url)
							uni.hideLoading()
						})
					})
				})
			},
			// 提交回答
			submitClick() {
				if (this.activeTab == 0) {
					if (!this.answerCon) {
						uni.showToast({
							icon: 'none',
							title: '请写下你的回答'
						})
						return
					}
				} else if (this.activeTab == 2) {
					if (!this.audioUrl) {
						return
						// uni.showToast({
						// 	icon: 'none',
						// 	title: '请录制音屏'
						// })
					}
				} else {
					if (!this.fileUrl) {
						uni.showToast({
							icon: 'none',
							title: '请上传视频'
						})
						return
					}
				}
				uni.showLoading({
					title: '提交中',
					mask: true
				})
				let param = {
					questionId: this.quesId,
					content: this.activeTab == 0 ? this.answerCon : '',
					imgUrl: this.activeTab == 0 ? (this.imgArr ? this.imgArr.join(',') : '') : '',
					videoUrl: this.activeTab == 0 ? '' : this.fileUrl,
					audioUrl:this.audioUrl
				}
				console.log('上传', param)
				addAnswer(param).then((res) => {
					if (res.code == 100000) {
						console.log('回答', res)
						this.delBtn()
						uni.navigateBack({
							delta: 1
						})
					}
					uni.hideLoading()
				}).catch((err) => {
					uni.hideLoading()
				})
			},
			// 倒计时
			countdown(val) {
				let _then = this;
				_then.count = Number(val);
				timer = setInterval(function() {
					if (_then.count > 0) {
						_then.count--
					} else {
						_then.longPress = '1';
						clearInterval(timer);
					}
				}, 1000);
			},
			// 长按录音事件
			longpressBtn() {
				this.longPress = '2';
				this.countdown(60); // 倒计时
				clearInterval(init) // 清除定时器
				recorderManager.onStop((res) => {
					this.tempFilePath = res.tempFilePath;
					this.recordingTimer(this.time);
				})
				const options = {
					duration: this.duration, // 指定录音的时长，单位 ms
					sampleRate: 16000, // 采样率
					numberOfChannels: 1, // 录音通道数
					encodeBitRate: 96000, // 编码码率
					format: 'mp3', // 音频格式，有效值 aac/mp3
					frameSize: 10, // 指定帧大小，单位 KB
				}
				this.recordingTimer();
				recorderManager.start(options);
				// 监听音频开始事件
				recorderManager.onStart((res) => {
					console.log(res)
				})
			},
			// 长按松开录音事件
			touchendBtn() {
				this.delShow = true;
				this.longPress = '1';
				recorderManager.onStop((res) => {
					this.tempFilePath = res.tempFilePath
				})
				this.recordingTimer(this.time)
				recorderManager.stop()
				setTimeout(()=>{
					console.log(this.tempFilePath,'111')
				},5000)
			},
			recordingTimer(time) {
				var that = this;
				if (time == undefined) {
					// 将计时器赋值给init
					init = setInterval(function() {
						that.time++
					}, 1000);
				} else {
					clearInterval(init)
				}
			},
			// 删除录音
			delBtn() {
				this.delShow = false;
				this.time = 0
				this.tempFilePath = ''
				this.playStatus = 0
				innerAudioContext.stop()
			},
			// 播放
			playBtn() {
				console.log(this.tempFilePath,'22')
				innerAudioContext.src = this.tempFilePath
				//在ios下静音时播放没有声音，默认为true，改为false就好了。
				// innerAudioContext.obeyMuteSwitch = false
				//点击播放
				if (this.playStatus == 0) {
					this.playStatus = 1;
					innerAudioContext.play();
					this.countdown(this.time); // 倒计时
				} else {
					this.playStatus = 0;
					innerAudioContext.pause()
				}
				// //播放结束
				innerAudioContext.onEnded(() => {
					this.playStatus = 0;
					innerAudioContext.stop();
				})
			},
			submitClick1(){
				uploadFile([this.tempFilePath]).then((successFile) => {
					console.log('文件', successFile)
					this.audioUrl = successFile.url
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	@import "@/static/public.scss";

	.quesType {
		padding: 0 150rpx;
		box-sizing: border-box;
	}

	#editor {
		width: 100%;
		height: 300px;
		background-color: #CCCCCC;
	}

	.uploadModule {

		.addBox {
			border: 2px dashed $colorccc;
			border-radius: 10rpx;
			width: 340rpx;
			height: 320rpx;
			margin: 100rpx auto 0;
			text-align: center;

			&>view {
				margin: 0 auto;
			}

			.timeOut {
				margin: 20rpx 0 0;
			}

			.audioOper {
				image {
					width: 50rpx;
					height: 50rpx;
				}

				&>view {
					margin: 50rpx auto 0;
				}

				.pause {
					margin: 0 40rpx;
				}
			}
		}
	}

	.rich {
		padding: 50rpx 30rpx 0;
		box-sizing: border-box;

		.imgBox {
			border-bottom: 1px solid $bordercolor;
			border-top: 1px solid $bordercolor;
			padding: 20rpx 0;

			image {
				width: 60rpx;
				height: 60rpx;
			}
		}
	}

	.hasVideo {
		video {
			height: 300rpx;
			width: 70%;
			display: block;
			margin: 100rpx auto 0;
		}
	}

	.hasAudio {
		::v-deep .uni-audio-right {
			display: block;
			margin: 0 auto;
			text-align: left;
		}
	}

	.noWidthBtn {
		width: 200rpx;
		padding: 10rpx 0;
		margin: 30rpx auto 0;
	}
	
	.audio{
		/* 语音录制开始--------------------------------------------------------------------- */
		.record-layer {
			width: 100%;
			padding: 300px 0 0;
			box-sizing: border-box;
			.record-box {
				width: 100%;
				position: relative;
				.btn{
					position: absolute;
					left: 100rpx;
					top: 0;
					font-size: 24rpx;
					width: 80rpx;
					height: 80rpx;
					background-color: #FFD300;
					border-radius: 80rpx;
					line-height: 80rpx;
					text{
						margin-left: 15rpx;
					}
				}
				.btn2{
					position: absolute;
					right: 100rpx;
					top: 0;
					font-size: 24rpx;
					width: 80rpx;
					height: 80rpx;
					background-color: #FFD300;
					border-radius: 80rpx;
					line-height: 80rpx;
					text{
						margin-left: 15rpx;
					}
				}
				.record-btn-layer {
					width: 100%;
					.record-btn{
						width: 200rpx;
						height: 100rpx;
						border-radius: 200rpx;
						font-size: 28rpx;
						line-height: 100rpx;
						text-align: center;
						background: #FFD300;
					}
				}
				.record-btn-layer button::after {
					border: none;
				}
			}
		}
		
		// .record-btn-layer button {
		// 	font-size: 28rpx;
		// 	line-height: 38rpx;
		// 	width: 200rpx;
		// 	height: 100px;
		// 	border-radius: 50px;
		// 	text-align: center;
		// 	background: #FFD300;
		// }
		
		.record-btn-layer button image {
			width: 16px;
			height: 16px;
			margin-right: 4px;
			vertical-align: middle;
		}
		
		.record-btn-layer .record-btn-2 {
			background: rgba(255, 211, 0, 0.2);
		}
		
		/* 提示小弹窗 */
		.prompt-layer {
			border-radius: 8px;
			background: #FFD300;
			padding: 8px 16px;
			box-sizing: border-box;
			position: absolute;
			left: 50%;
			transform: translateX(-50%);
		}
		
		.prompt-layer::after {
			content: '';
			display: block;
			border: 6px solid rgba(0, 0, 0, 0);
			border-top-color: rgba(255, 211, 0, 1);
			position: absolute;
			bottom: -10px;
			left: 50%;
			transform: translateX(-50%);
		}
		
		.prompt-layer-1 {
			font-size: 12px;
			width: 128px;
			text-align: center;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			top: -80px;
		}
		
		.prompt-layer-1 .p {
			color: #000000;
		}
		
		.prompt-layer-1 .span {
			color: rgba(0, 0, 0, .6);
		}
		
		.prompt-loader .em {}
		
		/* 语音音阶------------- */
		.prompt-loader {
			width: 96px;
			height: 20px;
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-bottom: 6px;
		}
		
		.prompt-loader .em {
			display: block;
			background: #333333;
			width: 1px;
			height: 10%;
			margin-right: 2.5px;
			float: left;
		}
		
		.prompt-loader .em:last-child {
			margin-right: 0px;
		}
		
		.prompt-loader .em:nth-child(1) {
			animation: load 2.5s 1.4s infinite linear;
		}
		
		.prompt-loader .em:nth-child(2) {
			animation: load 2.5s 1.2s infinite linear;
		}
		
		.prompt-loader .em:nth-child(3) {
			animation: load 2.5s 1s infinite linear;
		}
		
		.prompt-loader .em:nth-child(4) {
			animation: load 2.5s 0.8s infinite linear;
		}
		
		.prompt-loader .em:nth-child(5) {
			animation: load 2.5s 0.6s infinite linear;
		}
		
		.prompt-loader .em:nth-child(6) {
			animation: load 2.5s 0.4s infinite linear;
		}
		
		.prompt-loader .em:nth-child(7) {
			animation: load 2.5s 0.2s infinite linear;
		}
		
		.prompt-loader .em:nth-child(8) {
			animation: load 2.5s 0s infinite linear;
		}
		
		.prompt-loader .em:nth-child(9) {
			animation: load 2.5s 0.2s infinite linear;
		}
		
		.prompt-loader .em:nth-child(10) {
			animation: load 2.5s 0.4s infinite linear;
		}
		
		.prompt-loader .em:nth-child(11) {
			animation: load 2.5s 0.6s infinite linear;
		}
		
		.prompt-loader .em:nth-child(12) {
			animation: load 2.5s 0.8s infinite linear;
		}
		
		.prompt-loader .em:nth-child(13) {
			animation: load 2.5s 1s infinite linear;
		}
		
		.prompt-loader .em:nth-child(14) {
			animation: load 2.5s 1.2s infinite linear;
		}
		
		.prompt-loader .em:nth-child(15) {
			animation: load 2.5s 1.4s infinite linear;
		}
		
		@keyframes load {
			0% {
				height: 10%;
			}
		
			50% {
				height: 100%;
			}
		
			100% {
				height: 10%;
			}
		}
		
		/* 语音音阶-------------------- */
		.prompt-layer-2 {
			top: -40px;
		}
		
		.prompt-layer-2 .text {
			color: rgba(0, 0, 0, 1);
			font-size: 12px;
		}
		
		/* 语音录制结束---------------------------------------------------------------- */
	}
</style>